//
// Created on 2025/5/28.
//
// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found,
// please include "napi/native_api.h".

#include "oh/OHDrawingAPI.h"
#include <cstring>
#include <dlfcn.h>

#define DRAWING_SYMBOL_DEFINE(name, default_code, ret, ...)                                                            \
    OHDrawingAPI::name##Fun OHDrawingAPI::name = [](__VA_ARGS__) -> ret { default_code };                              \
    bool OHDrawingAPI::support_##name = false;
DRAWING_API_LIST(DRAWING_SYMBOL_DEFINE);
#undef DRAWING_SYMBOL_DEFINE

// used for symbol load.
static OHDrawingAPI api;

OHDrawingAPI::OHDrawingAPI() {
    fHandle[0] = dlopen("/system/lib64/libnative_drawing_ndk.z.so", RTLD_LAZY | RTLD_LOCAL);
    fHandle[1] = dlopen("/system/lib64/ndk/libimage_packer.so", RTLD_LAZY | RTLD_LOCAL);
    fHandle[2] = dlopen("/system/lib64/ndk/libimage_source.so", RTLD_LAZY | RTLD_LOCAL);
    loadAllSymblos();
}

OHDrawingAPI::~OHDrawingAPI() {
    for (int i = 0; i < fHandleCnt; i++) {
        dlclose(fHandle[i]);
    }
}

template <typename T> T OHDrawingAPI::loadSymbol(const char *symbolName) {
    for (int i = 0; i < fHandleCnt; i++) {
        auto symbol = dlsym(fHandle[i], symbolName);
        if (symbol) {
            return reinterpret_cast<T>(symbol);
        }
    }
    return nullptr;
}
